import { useImperativeHandle, forwardRef, Fragment, useState } from "react"
import { Form } from "antd"
import inputs from '../inputs'

const ComForm = ({
  formItems = [],
  onSubmit,
  labelCol = { span: 5 },
  wrapperCol = { span: 17 },
  disabled,
  ...props
}, ref) => {

  const [form] = Form.useForm()
  useImperativeHandle(ref, () => ({
    ...form,
  }))

  // 渲染表单函数
  const renderInput = (formItem) => {
    const inputTypes = Object.keys(inputs)

    let type = 'text'

    if (formItem.type) {
      if (typeof formItem.type === 'string') {
        if (inputTypes.includes(formItem.type)) {
          type = formItem.type
        }
      } else if (typeof formItem.type === 'function') {
        type = formItem.type(form)
        console.log(type)
      }
    }

    const FormInputName = inputs[type].component
    const inputProps = formItem.inputProps || {}

    return <FormInputName
      disabled={disabled}
      {...inputProps}
      onChange={(value) => {
        if (inputProps.onChange) {
          inputProps.onChange(value, form)
        }
      }}
    ></FormInputName>
  }

  // 获取表单验证规则
  const getFormItemRules = (formItem) => {
    let result = formItem.rules || []
    if (formItem.required) {
      result = [{ required: true, message: `${formItem.label}不能为空` }].concat(result)
    }
    return result
  }

  // 判断表单是否显示，用户表单之间相互的展示关系
  const checkItemShow = (formItem) => {
    let result = true
    if (formItem.hide && typeof formItem.hide === 'function') {
      return formItem.hide(form)
    }
    return result
  }

  const [a, setA] = useState(0)

  return <Form
    form={form}
    onFinish={onSubmit}
    labelCol={labelCol}
    wrapperCol={wrapperCol}
    onValuesChange={() => {
      if (formItems.some(el => !!el.hide || typeof el.type === 'function')) {
        setA((_a) => _a + 1)
      }
    }}
    {...props}
  >
    {
      formItems.map(el => {
        return <Fragment key={el.name}>
          {
            checkItemShow(el) &&
            <Form.Item
              name={el.name}
              label={el.label}
              rules={getFormItemRules(el)}
              {...el.props}
            >
              {renderInput(el)}
            </Form.Item>
          }
        </Fragment>
      })
    }
  </Form>
}

export default forwardRef(ComForm)